package com.futvan.z.framework.util;

import java.util.Date;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import com.futvan.z.framework.core.z;
import com.futvan.z.system.zworkjob.z_workjob;

public class JobUtil {
	/**
	 * 添加任务
	 * @param <T>
	 * @return
	 * @throws Exception 
	 * @throws Exception 
	 */
	public static void jobAdd(String JobId,String JobClass,String CronExpression) throws Exception{
		//创建任务
		@SuppressWarnings("unchecked")
		JobDetail job = JobBuilder.newJob((Class<? extends Job>) Class.forName(JobClass)).withIdentity(JobId, JobId+"-Detail-Group").build();
		//生成触发器
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(JobId+"-Trigger", JobId+"-Trigger-Group").startNow();
		//触发器时间设定  
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(CronExpression));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		//添加任务工厂
		z.job.scheduleJob(job, trigger);
	}
	
	/**
	 * 删除任务
	 * @param JobId
	 * @return
	 */
	public static void jobDelete(String JobId) throws Exception{
		TriggerKey triggerKey = TriggerKey.triggerKey(JobId+"-Trigger",JobId+"-Trigger-Group");
        // 停止触发器
		z.job.pauseTrigger(triggerKey);
        // 移除触发器
		z.job.unscheduleJob(triggerKey);
        // 删除任务
		z.job.deleteJob(JobKey.jobKey(JobId,JobId+"-Detail-Group"));
	}

	/**
	 * 运行任务(立即执行)
	 * @return
	 * @throws Exception 
	 * @throws Exception 
	 */
	public static void jobRun(String JobId,String JobClass) throws Exception{
		String tempNum = z.newNumber();
		@SuppressWarnings("unchecked")
		JobDetail job = JobBuilder.newJob((Class<? extends Job>) Class.forName(JobClass)).withIdentity(JobId+tempNum, JobId+"-Detail-Group").build();
		//创建执行时间
		Trigger trigger =  TriggerBuilder.newTrigger().withIdentity(JobId+tempNum+"-Now-Trigger" , JobId+tempNum+"-Now-Trigger-Group").withSchedule(SimpleScheduleBuilder.simpleSchedule()).startAt(new Date()).build();
		//添加job
		z.job.scheduleJob(job, trigger);
	}
}
